package com.jyhg.core.common.utils
{
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	
	public class ShareObjectTools
	{
		private static const HostName:String = "save";
		
		private static var _shareObj:SharedObject;
		public function ShareObjectTools()
		{
			
		}
		
		public static function get shareObj():SharedObject
		{
			if(!_shareObj)
			{
				_shareObj = SharedObject.getLocal(HostName);
			}
			return _shareObj;
		}
		
		/**
		 * 
		 * @param key
		 * @return 
		 * 
		 */
		public static function getObjectByKey(key:String):Object
		{
			return shareObj.data[key];
		}
		
		/**
		 *
		 * @param key
		 * @param value
		 * 
		 */
		public static function flush(key:String,value:*):void{
			if(shareObj.data)
			{
				shareObj.data[key] = value;
			}
			
			var flushStatus:String = null;
			try {
				flushStatus = shareObj.flush();
//				shareObj.close();
			} catch (error:Error) {
				throw error;
			}
			if (flushStatus != null) {
				switch (flushStatus) {
					case SharedObjectFlushStatus.PENDING:
						shareObj.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
						break;
					case SharedObjectFlushStatus.FLUSHED:
						break;
				}
			}
		}
		
		/**
		 *删除用户名下的所有数据 
		 * @param key
		 * 
		 */
		public static function clear(key:String):void
		{
			if(shareObj.data[key] != null)
			{
				shareObj.data[key] = null;
				shareObj.flush();
			}
		}
		private static function onFlushStatus(event:NetStatusEvent):void {
//			trace("User closed permission dialog...\n");
			switch (event.info.code) {
				case "SharedObject.Flush.Success":
//					trace("User granted permission -- value saved.\n");
					break;
				case "SharedObject.Flush.Failed":
//					trace("User denied permission -- value not saved.\n");
					break;
			}
			
			shareObj.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
		}
	}
}
